
package swengine;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Method;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 *
 * @author Patrik
 */
public class SAddon
{
	public void load()
	{
		File dir = new File("addons" + File.separator);
		if (!dir.isDirectory())
		{
			System.err.println("NO ADDONS FOLDER!");
			dir.mkdir();
			// There will not be any files in it as we just created it
			return;
		}

		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");

		for (Method m : Msg.class.getDeclaredMethods())
		{
			System.out.println("Added method: " + m.getName());
			engine.put(m.getName(), m);
		}

		for (File file : dir.listFiles())
		{
			if (file.isFile() && file.getName().endsWith(".js"))
			{
				try
				{
					System.out.println("Loading " + file.getName() + "...");
					engine.eval(new BufferedReader(new FileReader(file)));
				}
				catch (FileNotFoundException ex)
				{
					System.err.println("FAILED TO LOAD SCRIPT: " + file);
				}
				catch (ScriptException ex)
				{
					System.err.println("SCRIPT ERROR:");
					ex.printStackTrace();
				}
			}
		}
	}
}

class Msg
{
	public static void show(String arg)
	{
		javax.swing.JOptionPane.showMessageDialog(null, arg);
	}
}